package model

import (
	"log"
	"time"

	"github.com/bear/wolf/config"
	"github.com/bear/wolf/request"
	"github.com/bear/wolf/utils"
	"gorm.io/gorm"
)

type Task struct{
	Id 			int	   `json:"id" `
	ProjectId 	int `gorm:"column:project_id"  json:"projectId" `
	PId     	int `gorm:"column:p_id" json:"pId" `
	TaskName    string `gorm:"column:task_name" json:"taskName"`
	BeginAt     time.Time `json:"beginAt" `
	EndAt       time.Time `json:"endAt" `
	TaskType    int `json:"TaskType" `
	PlanTime    int `json:"planTime" `
	ActTime     int `json:"actTime" `
	CreateAt	time.Time `json:"createAt"`
	UpdateAt	time.Time	`json:"updateAt"`
}

func(T *Task) TableName() string{
	return "task"
}
//根据id删除
func DeleteByTaskId(id int) error{
	result := config.DB.Where("id = ?", id).Delete(&Task{})
	return result.Error
}

//create
func CreateTask(t *Task,userIds []int) error{
		return utils.WithTransaction(func(tx *gorm.DB) error {
			if err := tx.Create(t).Error; err != nil {
				return err // 发生错误时事务会自动回滚
			}
			taskId :=t.Id
			// 1. 在事务中调用删除函数
			if err := InsertTaskUser(tx,taskId,userIds); err != nil {
				return err // 发生错误时事务会自动回滚
			}
			// 3. 在事务中更新任务信息
			return nil
			})
}
func UpdateTaskId(t *Task,userIds []int) error{
	 return utils.WithTransaction(func(tx *gorm.DB) error {
        // 1. 在事务中调用删除函数
        if err := DeleteByProjectId(tx, t.Id); err != nil {
            return err // 发生错误时事务会自动回滚
        }
        // 2. 在事务中调用插入函数
        if err := InsertTaskUser(tx, t.Id, userIds); err != nil {
            return err // 发生错误时事务会自动回滚
        }
        // 3. 在事务中更新任务信息
        return tx.Where("id = ?", t.Id).Updates(t).Error
    })
}
//获取单个task
func GetTaskById(id int) Task{
	var task Task
	reuslt :=config.DB.Where("id=?",id).First(&task)
	if reuslt.Error !=nil{
		return Task{}
	}
	return task;
}
//根据名称获取
func GetTaskByname(taskname string)int64 {
	var count int64
	config.DB.Where("task_name =?", taskname).Count(&count)
	return count;
}
func GetTaskList(projectId,taskName,taskType string) []request.TaskList{
	query := config.DB.Table("task")
	if projectId !=""{
		query.Where("project_id =?",utils.StringToInt(projectId))
	}
	if taskName !=""{
		query.Where("task_name =?",taskName)
	}
	if taskType !=""{
		query.Where("task_type =?",utils.StringToInt(taskType))
	}
	var tasklist [] Task;
	query.Find(&tasklist)
	if len(tasklist)==0{
		return nil
	}
	var respList []request.TaskList
	for _, value := range  tasklist{

		projectName := GetProjectNameById(value.ProjectId)
		usernames := GetUserNmeByTaskId(value.Id)
		respList = append(respList, request.TaskList{
			Id :		value.Id,
			ProjectName: projectName,
			PId: 		value.PId,
			TaskName: value.TaskName,
			BeginAt: utils.FormatDate(value.BeginAt),
			EndAt: utils.FormatDate(value.EndAt),
			TaskType:value.TaskType,
			PlanTime : value.PlanTime,
			ActTime : value.ActTime,
			Usernames: usernames,
		})
	}
	
	return respList
}


func (t *Task) BeforeCreate(tx *gorm.DB) error {
    t.CreateAt = time.Now()
    t.UpdateAt = time.Now()
    return nil
}
func (t *Task) BeforeUpdate(tx *gorm.DB) error {
 
    t.UpdateAt = time.Now()
    return nil
}

func GetMyTaskList(userId int)[]request.MyTaskListVo{
	var tasks []Task
	//查询中间表
	tasknames := GetTaskNameByUserIdList(userId)

	config.DB.Table("task").
		Where("end_at > ?",time.Now()).
		Where("task_name in (?)",tasknames).Find(&tasks)
	if len(tasks) == 0 {
		return nil
	}
	var respList []request.MyTaskListVo
	for _, value := range tasks {
		projectName := GetProjectNameById(value.ProjectId)
		respList = append(respList, request.MyTaskListVo{
			Id :		value.Id,
			ProjectName: projectName,
			TaskName: value.TaskName,
			BeginAt: utils.FormatDate(value.BeginAt),
			EndAt: utils.FormatDate(value.EndAt),
			PlanTime : value.PlanTime,
			ActTime : value.ActTime,
		
		})
	}
	return respList
}
func GetTaskNameById(id int)string{
	var task Task
	config.DB.Table("task").Where("id=?",id).First(&task)
	return task.TaskName
}
//获取我的项目
func GetMyPorjectList(userId int)([]Project, error){
    var projects []Project
    
    // 使用JOIN一次性查询，减少数据库交互
    result := config.DB.Table("project p").
        Joins("JOIN task t ON p.id = t.project_id").
        Joins("JOIN user_task ut ON ut.task_id = t.id").
        Where("ut.user_id = ?", userId).
        Distinct("p.*"). // 去重，避免同一项目被多次返回
        Find(&projects)
    
    if result.Error != nil {
        // 记录错误日志
        log.Printf("获取用户项目列表失败: %v", result.Error)
        return nil, result.Error
    }  
    return projects, nil
}
